//
//  ForgetViewController.m
//  XDCommonApp
//
//  Created by wanglong8889@126.com on 14-3-11.
//  Copyright (c) 2014年 XD-XY. All rights reserved.
//

#import "ForgetViewController.h"
#import "XDTools.h"
#import "XDHeader.h"
#define XZB         22
@interface ForgetViewController ()

@end

@implementation ForgetViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self initViews];
	// Do any additional setup after loading the view.
}
-(void)initViews{
    
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.contentView.frame.size.width
                                                                     , self.contentView.frame.size.height)];
    _scrollView.scrollEnabled = NO;
    [self.contentView addSubview:_scrollView];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cancelPan)];
    [self.contentView addGestureRecognizer:tap];
    
    self.titleLabel.text = @"忘记密码";
    self.titleLabel.textColor = [UIColor blackColor];
    self.titleLabel.font = [UIFont systemFontOfSize:16.0];
    
    UILabel *titleLabel1 = [[UILabel alloc] initWithFrame:CGRectMake(XZB, 90,170, 22)];
    titleLabel1.text = @"你至少记住以下两项之一";
    titleLabel1.font = [UIFont fontWithName:@"Helvetica" size:15.0];
    titleLabel1.backgroundColor = [UIColor clearColor];
    [self.scrollView addSubview:titleLabel1];
    
    UILabel *emailLabel = [[UILabel alloc] initWithFrame:CGRectMake(XZB+6, titleLabel1.frame.origin.y+titleLabel1.frame.size.height+27, 170, 18)];
    emailLabel.font = [UIFont  systemFontOfSize:13.0];
    emailLabel.backgroundColor = [UIColor clearColor];
    emailLabel.text = @"您绑定的电子邮箱的地址";
    [self.scrollView addSubview:emailLabel];
    

    
    emailTf = [[UITextField alloc] initWithFrame:CGRectMake(XZB, emailLabel.frame.origin.y+emailLabel.frame.size.height+10,187, 28)];
    emailTf.borderStyle = UITextBorderStyleLine;
    emailTf.backgroundColor =  RGBA(168, 168, 168, 1.0);
    emailTf.font = [UIFont systemFontOfSize:13.0];
    emailTf.textColor = [UIColor whiteColor];
    if (IOS7) {
         emailTf.tintColor = [UIColor whiteColor];
    }
   
    emailTf.delegate = self;
    emailTf.returnKeyType = UIReturnKeyDone;
    emailTf.clearButtonMode = UITextFieldViewModeWhileEditing;
    emailTf.placeholder = @"请输入邮箱";
    [self.scrollView addSubview:emailTf];
    
    
    UILabel *sendLabel = [[UILabel alloc] initWithFrame:CGRectMake(emailTf.frame.origin.x+emailTf.frame.size.width+20, emailTf.frame.origin.y+5, 35, 18)];
    sendLabel.backgroundColor = [UIColor clearColor];
    sendLabel.textColor = [UIColor grayColor];
    sendLabel.text = @"发送";
    sendLabel.font = [UIFont systemFontOfSize:15.0];
    [self.scrollView addSubview:sendLabel];
    
    UIImageView *arImageView = [[UIImageView alloc] initWithFrame:CGRectMake(sendLabel.frame.origin.x+sendLabel.frame.size.width+6, sendLabel.frame.origin.y+1, 12, 18)];
    arImageView.image = [UIImage imageNamed:@"launh_sure"];
    [self.scrollView addSubview:arImageView];
    
    UIButton *sendPhoneBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    sendPhoneBtn.frame = CGRectMake(sendLabel.frame.origin.x, sendLabel.frame.origin.y-3, sendLabel.frame.size.width+arImageView.frame.size.width+5, sendLabel.frame.size.height+6);
    [sendPhoneBtn addTarget:self action:@selector(sendEmail) forControlEvents:UIControlEventTouchUpInside];
    [self.scrollView addSubview:sendPhoneBtn];
    
    
    
    
    UILabel *phoneLabel = [[UILabel alloc] initWithFrame:CGRectMake(XZB+6, emailTf.frame.origin.y+emailTf.frame.size.height+27,150, 18)];
    phoneLabel.text = @"您绑定的手机号码";
    phoneLabel.font = [UIFont systemFontOfSize:13.0];
    phoneLabel.backgroundColor = [UIColor clearColor];
    [self.scrollView addSubview:phoneLabel];
    
    phoneTf = [[UITextField alloc] initWithFrame:CGRectMake(XZB, phoneLabel.frame.origin.y+phoneLabel.frame.size.height+10,187, 28)];
    phoneTf.borderStyle = UITextBorderStyleLine;
    phoneTf.backgroundColor =  RGBA(168, 168, 168, 1.0);
    phoneTf.font = [UIFont systemFontOfSize:13.0];
    phoneTf.textColor = [UIColor whiteColor];
    if (IOS7) {
        phoneTf.tintColor = [UIColor whiteColor];
    }
    phoneTf.delegate = self;
    phoneTf.returnKeyType = UIReturnKeyDone;
    phoneTf.placeholder = @"请输入手机号";
    phoneTf.keyboardType = UIKeyboardTypeNumberPad;
    phoneTf.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self.scrollView addSubview:phoneTf];
    
    UILabel *sendLabel1 = [[UILabel alloc] initWithFrame:CGRectMake(phoneTf.frame.origin.x+phoneTf.frame.size.width+20, phoneTf.frame.origin.y+5, 35, 18)];
    sendLabel1.backgroundColor = [UIColor clearColor];
    sendLabel1.textColor = [UIColor grayColor];
    sendLabel1.text = @"发送";
    sendLabel1.font = [UIFont systemFontOfSize:15.0];
    [self.scrollView addSubview:sendLabel1];
    
    UIImageView *arImageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(sendLabel1.frame.origin.x+sendLabel1.frame.size.width+6, sendLabel1.frame.origin.y+1, 12, 18)];
    arImageView1.image = [UIImage imageNamed:@"launh_sure"];
    [self.scrollView addSubview:arImageView1];
    
    UIButton *sendPhoneBtn1 = [UIButton buttonWithType:UIButtonTypeCustom];
    sendPhoneBtn1.frame = CGRectMake(sendLabel1.frame.origin.x, sendLabel1.frame.origin.y-3, sendLabel1.frame.size.width+arImageView1.frame.size.width+5, sendLabel1.frame.size.height+6);
    [sendPhoneBtn1 addTarget:self action:@selector(sendPhone) forControlEvents:UIControlEventTouchUpInside];
    [self.scrollView addSubview:sendPhoneBtn1];

    
   
}
//发送邮箱
-(void)sendEmail{
    DDLOG(@"aa");
    BOOL isEmail = [self validateEmail:emailTf.text];
    if (!isEmail) {
        [XDTools showErrorTips:@"请输入合法邮箱重试" toView:self.contentView];
        
        return;
    }
    if ([XDTools NetworkReachable]){
        NSString *body = [NSString stringWithFormat:@" <Forgetpassword xmlns=\"http://tempuri.org/\">"
                          "<userinfor>%@</userinfor>"
                          "</Forgetpassword>",emailTf.text];
        
        __weak ASIFormDataRequest *request = [XDTools postRequestWithDict:body API:FORGETPASSWORD];
        [request setCompletionBlock:^{
            [XDTools hideProgress:self.contentView];
            //[XDTools hideProgress:self.contentView];
            NSString *responseString = [request responseString];
            // NSDictionary *tempDic = [XDTools  JSonFromString:responseString];
            DDLOG(@"responseString:%@", responseString);
            
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            int statusCode = [request responseStatusCode];
            NSString *soapAction = [[request requestHeaders] objectForKey:@"SOAPAction"];
            
            NSArray *arraySOAP =[soapAction componentsSeparatedByString:@"/"];
            int count = [arraySOAP count] - 1;
            NSString *methodName = [arraySOAP objectAtIndex:count];
            
            // Use when fetching text data
            NSString *result = nil;
            if (statusCode == 200) {
                //表示正常请求
                result = [SoapXmlParseHelper SoapMessageResultXml:responseString ServiceMethodName:methodName];
                NSDictionary  *responseDict = [XDTools JSonFromString:result];
                if ([[responseDict objectForKey:@"code"] intValue]==0){
                    DDLOG(@"res = %@",responseDict);
                    
                    [XDTools showTips:@"成功" toView:self.contentView];
                    [self.navigationController popViewControllerAnimated:YES];
                    
                }else{
                    [XDTools showTips:@"失败" toView:self.contentView];
                }
            }
        }];
        
        [request setFailedBlock:^{
            [XDTools hideProgress:self.contentView];
        }];
        
        [request startAsynchronous];
        [XDTools showProgress:self.contentView];
    }else{
        [XDTools showTips:brokenNetwork toView:self.contentView];
    }

    
}

-(void)sendPhone{
    if (phoneTf.text.length == 0||phoneTf.text == nil) {
        [XDTools showTips:@"账号不能为空" toView:self.view];
    }else{
        if (![self checkPhoneIsNum:phoneTf.text]) {
            [XDTools showTips:@"账号格式不对" toView:self.view];
        }else{
            [self mendPhone];
        }
    }
}
//发送手机号
-(void)mendPhone{
    DDLOG(@"bb");
    
    if ([XDTools NetworkReachable]){
        NSString *body = [NSString stringWithFormat:@" <Forgetpassword xmlns=\"http://tempuri.org/\">"
                          "<userinfor>%@</userinfor>"
                          "</Forgetpassword>",phoneTf.text];
        
        __weak ASIFormDataRequest *request = [XDTools postRequestWithDict:body API:FORGETPASSWORD];
        [request setCompletionBlock:^{
            [XDTools hideProgress:self.contentView];
            //[XDTools hideProgress:self.contentView];
            NSString *responseString = [request responseString];
            // NSDictionary *tempDic = [XDTools  JSonFromString:responseString];
            DDLOG(@"responseString:%@", responseString);
            
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            int statusCode = [request responseStatusCode];
            NSString *soapAction = [[request requestHeaders] objectForKey:@"SOAPAction"];
            
            NSArray *arraySOAP =[soapAction componentsSeparatedByString:@"/"];
            int count = [arraySOAP count] - 1;
            NSString *methodName = [arraySOAP objectAtIndex:count];
            
            // Use when fetching text data
            NSString *result = nil;
            if (statusCode == 200) {
                //表示正常请求
                result = [SoapXmlParseHelper SoapMessageResultXml:responseString ServiceMethodName:methodName];
                NSDictionary  *responseDict = [XDTools JSonFromString:result];
                if ([[responseDict objectForKey:@"code"] intValue]==0){
                    DDLOG(@"res = %@",responseDict);
                    
                    [XDTools showTips:@"成功" toView:self.contentView];
                    [self.navigationController popViewControllerAnimated:YES];
                    
                }else{
                    [XDTools showTips:@"失败" toView:self.contentView];
                }
            }
        }];
        
        [request setFailedBlock:^{
            [XDTools hideProgress:self.contentView];
        }];
        
        [request startAsynchronous];
        [XDTools showProgress:self.contentView];
    }else{
        [XDTools showTips:brokenNetwork toView:self.contentView];
    }
    

}

//校验电话是否是数字

-(BOOL)checkPhoneIsNum:(NSString *)str{
    [NSCharacterSet decimalDigitCharacterSet];
    
    
    if ([str stringByTrimmingCharactersInSet: [NSCharacterSet decimalDigitCharacterSet]].length >0) {
        
        //        DLog(@"不是纯数字");
        return NO;
        
    }else{
        if ([str length] == 11) {
            return YES;
        }else{
            return NO;
        }
        
        //        DLog(@"纯数字！");
        
    }
}
// 判断是否合法邮箱

- (BOOL) validateEmail: (NSString *) candidate {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:candidate];
}

-(void)back{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)cancelPan{
    [emailTf resignFirstResponder];
    [phoneTf resignFirstResponder];
    [UIView animateWithDuration:.3 animations:^{
        self.scrollView.contentOffset = CGPointMake(0, 0);
    }];
    
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self cancelPan];
    return YES;
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    [UIView animateWithDuration:.3 animations:^{
        self.scrollView.contentOffset = CGPointMake(0, 90);
    }];
    
    return  YES;
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
